const exepress = require('express');

const pool = require('../pool');
console.log(pool);

pool.query('SELECT * FROM xz_user', (err, result) => {
    if (err) {
        throw err;
    }
    console.log(result);
});

const router = exepress.Router();

router.post('/reg', (req, res, next) => {
    res.send({
        code: 200, 
        msg: '注册成功'
    });
});

router.post('/login', (req, res, next) => {
    //返回json
    let message = {
        code: 0,
        message: ""
    }

    //获取用户名和密码
    console.log(req.body);
    const user = {
        uname: req.body.uname,
        upwd: req.body.upwd
    }

    if (user.uname === undefined || user.upwd === undefined) {
        message.code = 401;
        message.message = "用户名和密码不能为空"
        res.send(message);
    }
    //验证登录
    pool.query("SELECT * FROM xz_user WHERE uname = ? AND upwd = ?", [user.uname, user.upwd], (err, result) => {
        if (err) {
            next(err);
            return;
        }

        if (result.length === 0) {
            message.code = 201;
            message.message = "用户名或密码不正确";
            res.send(message);
        } else {
            message.code = 200;
            message.message = "登录成功";
            res.send(message);
        }
    });
});

router.get("/:uid", (req, res, next) => {
    let uid = req.params.uid;
    pool.query("SELECT * FROM xz_user WHERE uid = ?", [uid], (err, result) => {
        if (err) {
            next(err);
            return;
        }

        if (result.length === 0) {
            res.send({
                code: 201, 
                msg: '该用户不存在',
            });
        } else {
            res.send({
                code: 200, 
                msg: '查询成功',
                data: [result[0]]
            });
        }
    })
});

router.delete("/:uid", (req, res, next) => {
    let uid = req.params.uid;
    pool.query("DELETE FROM xz_user WHERE uid = ?", [uid], (err, result) => {
        if (err) {
            next(err);
            return;
        }

        if (result.affectedRows === 1) {
            res.send({
                code: 200, 
                msg: '删除成功',
            });
        } else {
            res.send({
                code: 201, 
                msg: '删除失败',
            });
        }
    })

});

module.exports = router;